package com.nd.qa.shareplate.util;

import java.io.File;


import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 文件压缩解压类
 * @version 1.00 wuqiaomin 新建
 */

public class FileZip {

	private File zipFile;

	public FileZip(String pathName) {
		zipFile = new File(pathName);
	}

	public void compress(String srcPathName, String includesName) {
		File srcdir = new File(srcPathName);
		if (!srcdir.exists()){
			throw new RuntimeException(srcPathName + "不存在！");
		}
		Project prj = new Project();
		Zip zip = new Zip();
		zip.setProject(prj);
		zip.setDestFile(zipFile);
		zip.setEncoding("UTF-8");
		FileSet fileSet = new FileSet();
		fileSet.setProject(prj);
		fileSet.setDir(srcdir);
		fileSet.setIncludes(includesName+"/"); //包括哪些文件或文件夹 */，会使得前缀相同的文件都包含进来了  ( "*"+includesName+"/")
		// eg:zip.setIncludes("*.java");
		fileSet.setExcludes("*.zip"); //排除哪些文件或文件夹
		zip.addFileset(fileSet);
		zip.execute();
	}
	
	   public  void ZIPDIR(String sourceDir, ZipOutputStream zos,String tager) throws IOException {
	        // System.out.println(tager);
	        ZipEntry ze = new ZipEntry(tager);
	        zos.putNextEntry(ze);
	        // 提取要压缩的文件夹中的所有文件
	        File f = new File(sourceDir);
	        File[] flist = f.listFiles();
	        if (flist != null) {
	        // 如果该文件夹下有文件则提取所有的文件进行压缩
	            for (File fsub : flist) {
	                if (fsub.isDirectory()) {
	                    // 如果是目录则进行目录压缩
	                    ZIPDIR(fsub.getPath(), zos, tager + fsub.getName() + "/");
	                }else{
	                    // 如果是文件，则进行文件压缩
	                    ZIPFile(fsub.getPath(), zos, tager + fsub.getName());
	                }
	            }
	        }
	    }

	    
	    public  void ZIPFile(String sourceFileName, ZipOutputStream zos,String tager) throws IOException {
	         // System.out.println(tager);
	         ZipEntry ze = new ZipEntry(tager);
	         zos.putNextEntry(ze);
	         // 读取要压缩文件并将其添加到压缩文件中
	         FileInputStream fis = new FileInputStream(new File(sourceFileName));
	         byte[] bf = new byte[2048];
	         int location = 0;
	         while ((location = fis.read(bf)) != -1) {
	             zos.write(bf, 0, location);
	         }
	         fis.close();
	    }
}
